package com.lemon.stock.compose.mine

import android.annotation.SuppressLint
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.R
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lemon.stock.compose.ListItemDivider
import com.lemon.stock.compose.StockBaseInfo
import com.lemon.stock.compose.StockImage
import com.lemon.stock.compose.StockTrades
import com.lemon.stock.entity.Batch
import com.lemon.stock.entity.Stock
import com.lemon.stock.entity.Trade
import com.lemon.stock.entity.TradeDeleteState
import com.lemon.stock.theme.*
import com.lemon.stock.util.showMessage
import com.lemon.stock.viewmodel.HistoryViewModel
import com.lemon.stock.viewmodel.StocksViewModel
import java.text.SimpleDateFormat
import java.util.*

@Composable
fun HistoryScreen(backDispatcher: OnBackPressedDispatcher, onBack: () -> Unit){
    val stockState = rememberSaveable{ mutableStateOf("") }
    val mViewModel: HistoryViewModel = viewModel()
    val currentOnBack by rememberUpdatedState(onBack)

    //重写用户返回上一级，参考：https://developer.android.google.cn/jetpack/compose/side-effects
    val backCallback = remember {
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if(stockState.value != ""){
                    stockState.value = ""
                }else{
                    currentOnBack()
                }
            }
        }
    }
    DisposableEffect(backDispatcher) {
        backDispatcher.addCallback(backCallback)
        onDispose {
            backCallback.remove()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("股票列表") },
                elevation = 8.dp,
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Filled.ArrowBack, contentDescription = null)
                    }
                }
            )
        }
    ){
        if(stockState.value == ""){
            StockItems(mViewModel, stockState)
        }else{
            StockDetail(mViewModel, stockState)
        }
    }
}

/**
 * 股票列表
 */
@Composable
fun StockItems(mViewModel: HistoryViewModel, stockState: MutableState<String>){
    val stocks = mViewModel.stocks.observeAsState(arrayListOf())
    mViewModel.fetchStocks()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(8.dp)
    ){
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .fillMaxWidth()
                .height(38.dp)
        ){
            Text(stringResource(id = com.lemon.stock.R.string.stock_name), style = styleHead, modifier = Modifier.weight(1f))
            Text(stringResource(id = com.lemon.stock.R.string.stock_id), style = styleHead, modifier = Modifier.weight(1f))
            Text(stringResource(id = com.lemon.stock.R.string.stock_profit), style = styleHead, modifier = Modifier.weight(1f))
            Text(stringResource(id = com.lemon.stock.R.string.stock_follow), style = styleHead, modifier = Modifier.weight(1f))
        }

        ListItemDivider()

        LazyColumn(
            modifier = Modifier.padding(bottom = 10.dp)
        ){
            items(items = stocks.value){stock->
                var checked by remember { mutableStateOf(stock.follow == 8) }
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(44.dp)
                ){
                    Row(
                        modifier = Modifier
                            .weight(3f)
                            .clickable {
                                stockState.value = stock.stockId
                            }

                    ){
                        Text(text = stock.stockName, style = styleBold, modifier = Modifier.weight(1f))
                        Text(text = stock.stockId, style = styleBody, modifier = Modifier.weight(1f))
                        Text(text = String.format("%.2f", stock.totalProfit), style = styleBodyRight, modifier = Modifier.weight(1f))
                    }

                    //Text(text = "", style = styleBody, modifier = Modifier.weight(1f))
                    Checkbox(
                        checked = checked,
                        modifier = Modifier
                            .padding(8.dp)
                            .weight(1f)
                            .alpha(0.3f),
                        onCheckedChange = {
                            checked = !checked
                            stock.follow = (if(checked) 8 else 4)
                            mViewModel.updateStock(stock)
                        })
                }
                ListItemDivider()
            }
        }
    }
}

@Composable
fun StockDetail(mViewModel: HistoryViewModel, stockState: MutableState<String>){

    val stockId = stockState.value
    val vStock = mViewModel.stock.observeAsState()
    val batches = mViewModel.batches.observeAsState(arrayListOf())
    val trades = mViewModel.trades.observeAsState(arrayListOf())
    val indexState = rememberSaveable { mutableStateOf(-1)}
    val deleteTradeState = remember { mutableStateOf(TradeDeleteState(0L))} //此处只做声明，暂不用

    mViewModel.fetchStock(stockId)

    mViewModel.fetchBatches(stockId)
    mViewModel.fetchTrades(stockId, indexState.value)

    if(vStock.value != null){
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(8.dp)
        ){
            item{
                StockBaseInfo(vStock = vStock.value!!)

                Spacer(modifier = Modifier.height(15.dp))

                Text(text = "投资批次")
                StockBatches(batches, indexState)

                Spacer(modifier = Modifier.height(15.dp))
                Text(text = "购买记录")

                StockTrades(vStock = vStock.value!!, deleteTradeState, trades)

                Spacer(modifier = Modifier.height(50.dp))
            }
        }
    }

}

@Composable
fun StockBatches(batches: State<List<Batch>>, indexState: MutableState<Int>){
    val formatDate = SimpleDateFormat("yyyy.MM.dd")
    val index = indexState.value

    ListItemDivider()
    Row(
        modifier = Modifier.padding(vertical= 4.dp)
    ){
        Text(stringResource(id = com.lemon.stock.R.string.btn_buy) + "/" + stringResource(id = com.lemon.stock.R.string.btn_sell), style = styleHead, modifier = Modifier.weight(2f))
        Text(stringResource(id = com.lemon.stock.R.string.text_amount), style = styleHead, modifier = Modifier.weight(1f))
        Text(stringResource(id = com.lemon.stock.R.string.text_money), style = styleHead, modifier = Modifier.weight(2f))
        Text(stringResource(id = com.lemon.stock.R.string.stock_gain) + "/" + stringResource(id = com.lemon.stock.R.string.stock_gain_ratio), style = styleHead, modifier = Modifier.weight(2f))
    }

    ListItemDivider()

    batches.value.forEach(){batch->
        val batchStyle = when(batch.investIndex == index){
            true -> styleBodyRight
            false -> styleLowerRight
        }
        Column(
            //verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.padding(vertical = 0.dp).height(56.dp).clickable {
                indexState.value = batch.investIndex
            }
        ){
            var ratio = 0f
            if(batch.totalInvest>0){
                ratio = (batch.profitMoney*10000/batch.totalInvest).toInt().toFloat()/100
            }
            Row(

            ){
                Text(text = formatDate.format(Date(batch.inDate)), style = batchStyle, modifier = Modifier.weight(1f))
                Text(text = batch.maxAmount.toString(), style = batchStyle, modifier = Modifier.weight(1f))
                Text(text = String.format("%.2f", batch.maxInvest), style = batchStyle, modifier = Modifier.weight(1f))
                Text(text = String.format("%.2f", batch.profitMoney), style = batchStyle, modifier = Modifier.weight(1f))
            }
            Row(){
                Text(text = formatDate.format(Date(batch.outDate)), style = batchStyle, modifier = Modifier.weight(1f))
                Text(text = batch.totalAmount.toString(), style = batchStyle, modifier = Modifier.weight(1f))
                Text(text = String.format("%.2f", batch.totalInvest), style = batchStyle, modifier = Modifier.weight(1f))
                Text(text = String.format("%.2f", ratio)+"%", style = batchStyle, modifier = Modifier.weight(1f))
            }
        }
        ListItemDivider()
    }
}
